package cn.edu.cdtu.healthserver.servlet;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Element;
import org.dom4j.Node;

import cn.edu.cdtu.healthserver.domain.NewsFromInternet;
import cn.edu.cdtu.healthserver.service.InternetHealthNewsService;
import cn.edu.cdtu.healthserver.service.impl.InternetHealthNewsServiceImplementation;
import cn.edu.cdtu.healthserver.utils.ConnectUtil;
import cn.edu.cdtu.healthserver.utils.XmlUtil;

/**
 * Servlet implementation class GetNewsFromInternetServlet
 */
@WebServlet("/GetNewsFromInternetServlet")
public class GetNewsFromInternetServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetNewsFromInternetServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		String  chinese = "[\\u4e00-\\u9fa5]";
		Pattern pattern = Pattern.compile(chinese);
		Matcher matcher;
		URL url=null;
		XmlUtil xmlUtil=new XmlUtil();
		NewsFromInternet newsFromInternet=new NewsFromInternet();
		InternetHealthNewsService internetHealthNewsService=new InternetHealthNewsServiceImplementation();
		
		ArrayList<String> urlList = new ArrayList<String>();
		urlList.add("http://news.baidu.com/n?cmd=4&class=jiankang&tn=rss");
		
		Iterator<String> urlListIterator = urlList.iterator();
		while(urlListIterator.hasNext())
		{
			url=new URL((String)urlListIterator.next());
			List<?> xmlInformation=xmlUtil.getXmlInformation("//channel/item", url);
			
			int newsNumber=0;
			
			for(Iterator<?> iterator=xmlInformation.iterator();iterator.hasNext();)
			{
				newsNumber++;
				if(newsNumber>10)
				{
					break;
				}
				
				Element element = (Element) iterator.next();
				Node description = element.selectSingleNode("description");
				matcher = pattern.matcher(description.getText().toString());
				int index = 0;
				if(matcher.find())
				{
					description.setText(description.getText() + "...");
					index = description.getText().indexOf(matcher.group());	
					
				}
				int i = description.getText().indexOf("...");
				String descriptionOfChinese = description.getText()
						.substring(index,
								i+3);
				Node pubDate=element.selectSingleNode("pubDate");
				Node title = element.selectSingleNode("title");				
				Node link = element.selectSingleNode("link");
				
				newsFromInternet.setDescription(descriptionOfChinese);
				newsFromInternet.setPubDate(pubDate.getText());
				newsFromInternet.setTitle(title.getText());
				newsFromInternet.setLink(link.getText());
				
				internetHealthNewsService.addInternetNews(newsFromInternet);
			}
		}
		List<NewsFromInternet> allNewsList=internetHealthNewsService.queryInternetNews();
		xmlUtil.generateXML(allNewsList, request.getSession().getServletContext().getRealPath("")+"\\");
		request.getSession().setAttribute(ConnectUtil.Admin.Result.RESULT_MESSAGE, 
				"更新新闻成功");
		response.sendRedirect(ConnectUtil.Admin.ADMIN_JSP_NEWS);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request,response);
	}

}
